package com.dream.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 匠人码农
 * @date 2020/11/06 15:27
 * 概要：
 *      Filter方式进行用户登陆的验证
 */

public class AdminFilter implements Filter {

    /**
     * 构造方法
     */
    public AdminFilter() {
        System.out.println("AdminFilter构造器被执行了！");
    }

    /**
     * 初始化方法
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("AdminFilter的初期化完成了！");

        //获取Filter的名称
        System.out.println("获取Filter名称：" + filterConfig.getFilterName());

        //获取初始化参数
        System.out.println("初始化参数key：" + filterConfig.getInitParameter("key"));

        //获取ServletContext
        System.out.println("ServletContext:" + filterConfig.getServletContext());

        //获取servletcontext对象的contextpath值
        System.out.println("servletcontext的对象某些值：" + filterConfig.getServletContext().getContextPath());

    }

    /**
     *
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        System.out.println("AdminFilter过滤器的doFilter方法被执行了！");

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpSession httpSession = httpServletRequest.getSession();
        //获取用户名
        String user = (String) httpSession.getAttribute("username");
        if(user == null){
            //请求转发到登录页面
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            return;
        }else{
            //通过执行链往下执行目标资源
            chain.doFilter(request,response);
        }
    }

    /**
     * 销毁方法
     */
    @Override
    public void destroy() {
        System.out.println("AdminFilter的销毁执行了！");
    }
}
